﻿using Microsoft.Research.DynamicDataDisplay;
using Microsoft.Research.DynamicDataDisplay.DataSources;
using System;
using System.Collections.Generic;
using System.IO.Ports;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Threading;

namespace ExperimentTwo
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        //portsArray数组获得所有串口列表  
        string[] portsArray = SerialPort.GetPortNames();
        SerialPort serialPort = new SerialPort();
        public delegate void Displaydelegate(byte[] InputBuf);
        Byte[] OutputBuf = new Byte[128];
        public Displaydelegate disp_delegate;
        private ObservableDataSource<Point> temp_dataSource = new ObservableDataSource<Point>();
        private ObservableDataSource<Point> light_dataSource = new ObservableDataSource<Point>();
        private DispatcherTimer timer = new DispatcherTimer();
        private int i = 0;
        private List<string> receiveSource = new List<string>(); 

        public class Data
        {
            public string temp;
            public string light;
        }
        Data data = new Data();

        public MainWindow()
        {
            InitializeComponent();
            foreach (string port in portsArray)
            {
                ComboBox_Port.Items.Add(port);
            }
            ComboBox_Rate.Items.Add(9600);
            ComboBox_Rate.Items.Add(19200);
            ComboBox_Rate.Items.Add(38400);
            ComboBox_Rate.Items.Add(57600);
            blue_slider.Maximum = 255;
        }

        private void ComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            
        }

        private void ComboBox_SelectionChanged_1(object sender, SelectionChangedEventArgs e)
        {
        }

        private void TextBox_TextChanged(object sender, TextChangedEventArgs e)
        {

        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {

        }

        private void Button_Click_2(object sender, RoutedEventArgs e)
        {
            try
            {
                string port = this.ComboBox_Port.SelectedItem.ToString();
                string rate = this.ComboBox_Rate.SelectedItem.ToString();
                serialPort.ReceivedBytesThreshold = 1;
                serialPort.Encoding = Encoding.ASCII;
                serialPort.PortName = port;
                serialPort.BaudRate = int.Parse(rate);
                if (!serialPort.IsOpen)
                {
                    serialPort.Open();
                    MessageBox.Show("连接成功");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void Button_Click_5(object sender, RoutedEventArgs e)
        {
            portWrite("00");
        }

        private void Button_Click_6(object sender, RoutedEventArgs e)
        {
            portWrite("01");
        }

        private void Button_Click_3(object sender, RoutedEventArgs e)
        {
            if (serialPort.IsOpen)
            {
                try
                {
                    serialPort.Close();
                    serialPort.Dispose();
                    MessageBox.Show("断开成功");
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }
            else
            {
                MessageBox.Show("当前未连接到开发板");
            }
        }

        private void Button_Click_4(object sender, RoutedEventArgs e)
        {
            int val_red = (int)red_slider.Value;
            int val_green = (int)green_silder.Value;
            int val_yellow = (int)yellow_slider.Value;
            int val_blue = (int)blue_slider.Value;
            int val_white = (int)white_slider.Value;
            MessageBox.Show("红灯亮度： "+val_red.ToString() + "\n"
                + "绿灯亮度： " + val_green.ToString() + "\n"
                + "黄灯亮度： " + val_yellow.ToString() + "\n"
                + "蓝灯亮度： " + val_blue.ToString() + "\n"
                + "白灯亮度： " + val_white.ToString() + "\n");

            string light_red = (255 - val_red).ToString();
            string light_green = (255 - val_green).ToString();
            string light_yellow = (255 - val_yellow).ToString();
            string light_blue = (255 - val_blue).ToString();
            string light_white = (255 - val_white).ToString();
            portWrite("l"); //Arduino里的way参数, l表示控制小灯亮度
            portWrite(light_red);
            portWrite("l");
            portWrite(light_green);
            portWrite("l");
            portWrite(light_yellow);
            portWrite("l");
            portWrite(light_blue);
            portWrite("l");
            portWrite(light_white);
        }

        private void Slider_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
        {
        }

        private void portWrite(string message)
        {
            if (serialPort.IsOpen)
            {
                serialPort.Write(message);
            }
        }

        private void ListView_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
        }

        private void ListView_SelectionChanged_1(object sender, SelectionChangedEventArgs e)
        {

        }

        private void ListView_SelectionChanged_2(object sender, SelectionChangedEventArgs e)
        {

        }

        private void ListView_SelectionChanged_3(object sender, SelectionChangedEventArgs e)
        {

        }

        private void Button_Click_1(object sender, RoutedEventArgs e)
        {
            
        }

        private void receive_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                serialPort.DataReceived += serialPort_DataReceived;
                temp_plotter.AddLineGraph(temp_dataSource, Colors.Green, 2, "temp");
                light_plotter.AddLineGraph(light_dataSource, Colors.Green, 2, "light");

                timer.Interval = TimeSpan.FromSeconds(1);
                timer.Tick += new EventHandler(AnimatedPlot);
                timer.IsEnabled = true;

                temp_plotter.Viewport.FitToView();
                light_plotter.Viewport.FitToView();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void serialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            try
            {
                string value = this.portRead();
                if (value[0] < '8')
                {
                    temp_textBox.Dispatcher.Invoke(new Action(() =>
                    {
                        data.temp = value;
                        temp_textBox.AppendText(value);
                        temp_textBox.ScrollToEnd();
                    }));
                }
                else
                {
                    light_textBox.Dispatcher.Invoke(new Action(() =>
                    {
                        data.light = value;
                        light_textBox.AppendText(value);
                        light_textBox.ScrollToEnd();
                    }));
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        

        private string portRead()
        {
            string value = "";
            try
            {
                if (serialPort.IsOpen && serialPort.BytesToRead > 0)
                {
                    value = serialPort.ReadLine();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            return value;
        }

        private void AnimatedPlot(object sender, EventArgs e)
        {
            double x = i;
            if (data.temp != null)
            {
                double y = double.Parse(data.temp);
                Point point = new Point(x, y);
                temp_dataSource.AppendAsync(base.Dispatcher, point);
            }
            if (data.light != null)
            {
                double y = double.Parse(data.light);
                Point point = new Point(x, y);
                light_dataSource.AppendAsync(base.Dispatcher, point);
            }
            i++;
        }
    }
}
